/*
   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
 */
package com.zavakid.scala.exercise.chapter14

/**
 * @author zavakid 2013-6-15 下午1:37:47
 * @since 1.0
 */
object Main14 extends App {

  def no2(x: (Int, Int)): (Int, Int) = {
    x match {
      case (a, b) => (b, a)
    }
  }

  def no3(array: Array[_]) = {
    array match {
      case _ if (array.length < 2) => throw new IllegalArgumentException("array's length must >= 2")
      case Array(x, y, left @ _*) => Array(y, x) ++ left
    }
  }

  def no5(array: Array[Any]): Int = array match {
    case Array() => 0
    case Array(x: Int, tail @ _*) => x + no5(tail.toArray)
    case Array(Array(inner @ _*), tail @ _*) => no5(inner.toArray) + no5(tail.toArray)
    case _ => throw new IllegalArgumentException
  }

  def no6(tree: BinaryTree): Int = tree match {
    case Leaf(x) => x
    case Node(x, y) => no6(x) + no6(y)
  }

  def no7(tree: BinaryTree): Int = tree match {
    case Leaf(x) => x
    case Node(x @ _*) => x.foldLeft(0)((init, el) => init + no7(el))
  }

  def no8(tree: BinaryTree): Int = tree match {
    case Leaf(x) => x
    case Node(Leaf(x)) => x
    case Node(OP_PLUS(), x @ _*) => x.foldLeft(0)(_ + no8(_))
    case Node(OP_SUB(), x @ _*) => x.foldLeft(0)(_ - no8(_))
    case Node(OP_MULTI(), x @ _*) => x.foldLeft(1)(_ * no8(_))
  }
  //  val node = Node(OP_PLUS(), Node(OP_MULTI(), Leaf(3), Leaf(8)), Leaf(2), Node(OP_SUB(), Leaf(5)))
  //  println(no8(node))

  def no9(x: List[Option[Int]]): Int = {
    var sum = 0
    for (i <- x) {
      i.foreach(sum += _)
    }
    sum
  }
  //  val list = List(Some(1), None, Some(2), None, Some(3), Some(4))
  //  println(no9(list))

  def no10(f: (Double) => Option[Double], g: (Double) => Option[Double])(input: Double): Option[Double] = (f(input), g(input)) match {
    case (Some(x), Some(y)) => Some(y)
    case _ => None
  }
}